<template>
  <div class="bg-white sticky top-0 left-0 z-10 dark:bg-zinc-900">
    <ul
      ref="ulTargetRef"
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
    >
      <!-- 滑块 -->
      <li
        ref="sliderTarget"
        :style="sliderStyle"
        class="absolute h-[22px] rounded-lg bg-zinc-900 duration-200 dark:bg-zinc-800"
      ></li>
      <!-- 汉堡按钮 -->
      <li
        @click="isShowPopup"
        class="dark:bg-zinc-900 dark:shadow-l-zinc fixed top-0 right-[-1px] h-3 px-1 pt-[12px] flex items-center bg-white z-20 shadow-l-white"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger" />
      </li>
      <!-- items  -->
      <li
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
        v-for="(item, index) in $store.getters.categoryList"
        :key="item.id"
        :ref="setItemsRef"
        :class="{
          'text-zinc-100': $store.getters.currentCategoryIndex == index
        }"
        @click="itemCLick(item)"
      >
        {{ item.name }}
      </li>
    </ul>
    <m-popup v-model="isVisible">
      <MenuVue @itemCLick="itemCLick" />
    </m-popup>
  </div>
</template>

<script setup>
import { ref, onBeforeUpdate, watch } from 'vue'
import { useScroll } from '@vueuse/core'
import MenuVue from '@/views/main/components/menu/index.vue'
import { useStore } from 'vuex'
const store = useStore()
// const props = defineProps({
//   data: {
//     type: Array,
//     required: true
//   }
// })
const sliderTarget = ref(null)
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '47px'
})
// const currentIndex = ref(0)

const itemCLick = (item) => {
  // currentIndex.value = index
  store.commit('app/changeCurrentCategory', item)
  isVisible.value = false
}
const itemsRef = ref([])
// 获取v-for 循环的数据的元素，不能直接使用ref 需要使用一个函数来接收
const setItemsRef = (el) => {
  if (el) {
    itemsRef.value.push(el)
  }
}
// 不能让数据一直推，在数据更新后，dom 更新前将数组清空
onBeforeUpdate(() => {
  itemsRef.value = []
})

// 计算滑块的偏移量
// 先获取 ul 的元素，计算需要滚动的位置
const ulTargetRef = ref(null)

const { x: scrollLeft } = useScroll(ulTargetRef)
watch(
  () => store.getters.currentCategoryIndex,
  (val) => {
    let { left, width } = itemsRef.value[val].getBoundingClientRect()
    sliderStyle.value = {
      transform: `translateX(${left + scrollLeft.value - 10}px)`,
      width: width + 'px'
    }
  }
)

const isVisible = ref(false)
const isShowPopup = () => {
  isVisible.value = true
}
</script>
<!-- <style scoped lang="scss"></style> -->
